/*
 * @(#) $Header$
 *
 * Copyright (C) 2007  Forklabs Daniel Léonard
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package ca.forklabs.media.jai.opimage;

import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.util.Collection;
import javax.media.jai.CollectionImage;
import javax.media.jai.CollectionImageFactory;
import javax.media.jai.CollectionOp;
import javax.media.jai.JAI;
import ca.forklabs.media.jai.CollectionImageUtil;
import ca.forklabs.media.jai.FormatDataType;
import ca.forklabs.media.jai.ParameterBlockUtil;
import ca.forklabs.media.jai.SimpleCollectionImage;
import ca.forklabs.media.jai.SpectralFilter3D;
import ca.forklabs.media.jai.operator.PeriodicShift3DDescriptor;
import ca.forklabs.media.jai.operator.PipelineDescriptor;
import ca.forklabs.media.jai.operator.SpectralHomomorphicDescriptor;

/**
 * Class {@code SpectralFilterCIF} is a {@link CollectionImageFactory}
 * supporting the <em>spectralfilter</em> operation.
 *
 * @author   <a href="mailto:forklabs at gmail.com?subject=ca.forklabs.media.jai.opimage.SpectralFilterCIF">Daniel Léonard</a>
 * @version $Revision$
 */
public class SpectralFilterCIF implements CollectionImageFactory {

//---------------------------
// Constructor
//---------------------------

   /**
    * Constructor.
    */
   public SpectralFilterCIF() {
   // nothing
      }


//---------------------------
// Instance methods
//---------------------------

   /**
    * Gets the spectral filter.
    * @param   pb   the parameter block.
    * @return   the spectral filter.
    */
   protected SpectralFilter3D getFilter(ParameterBlock pb) {
      int index = SpectralHomomorphicDescriptor.FILTER_PARAMETER_INDEX;
      SpectralFilter3D filter = (SpectralFilter3D) pb.getObjectParameter(index);
      return filter;
      }

   /**
    * Gets the type for the format operation.
    * @param   pb   the parameter block.
    * @return   type for the format operation.
    */
   protected int getDataType(ParameterBlock pb) {
      int index = SpectralHomomorphicDescriptor.TYPE_PARAMETER_INDEX;
      FormatDataType format = (FormatDataType) pb.getObjectParameter(index);
      int type = format.getDataBufferType();
      return type;
      }

   /**
    * Does a periodic shift of half the image size in all three dimensions.
    * @param sources   the images to shift.
    * @param hints   the rendering hints.
    * @return   the shifted image.
    */
   protected CollectionImage shift(CollectionImage sources, RenderingHints hints) {
      String operation = PeriodicShift3DDescriptor.NAME;
      ParameterBlock pb = new ParameterBlock().addSource(sources);
      Collection<?> images = JAI.createCollection(operation, pb, hints);
      CollectionImage sink = CollectionImageUtil.asCollectionImage(images);
      return sink;
      }

   /**
    * Builds the centered filter image.
    * @param   filter   the filter.
    * @param   width   the desired width.
    * @param   height   the desired height.
    * @param   depth   the desired depth.
    * @param   elements   the number of elements, half the number of bands.
    * @param   hints   the rendering hints.
    * @return   the filter image.
    */
   protected CollectionImage getRawFilter(SpectralFilter3D filter, int width, int height, int depth, int elements, RenderingHints hints) {
      filter.setWidth(width);
      filter.setHeight(height);
      filter.setDepth(depth);
      CollectionImage sink = filter.getFilterImage(elements, hints);
      return sink;
      }

   @SuppressWarnings("nls")
   protected CollectionImage multiply(CollectionImage sources0, CollectionImage sources1, RenderingHints hints) {
// BUG : make a new collection descriptor for multiply complex that adds a collection mode
      CollectionImage sinks = new SimpleCollectionImage();

      int len = sources0.size();
      RenderedImage[] images0 = (RenderedImage[]) sources0.toArray(new RenderedImage[len]);
      RenderedImage[] images1 = (RenderedImage[]) sources1.toArray(new RenderedImage[len]);

      for (int i = 0; i < len; i++) {
         RenderedImage source0 = images0[i];
         RenderedImage source1 = images1[i];

         ParameterBlock pb = ParameterBlockUtil.createMultiplyComplexParameterBlock(source0, source1);
         RenderedImage sink = JAI.create("multiplycomplex", pb, hints);

         sinks.add(sink);
         }

      return sinks;
      }

   /**
    * Filters the Fourier image.
    * @param   sources   the Fourier images.
    * @param   filter   the filter.
    * @param   hints   the rendering hints.
    * @return   the spectral image filtered.
    */
   protected CollectionImage filter(CollectionImage sources, SpectralFilter3D filter, RenderingHints hints) {
// TODO : simplify when issue 102 of jai-core is resolved
      //RenderedImage image0 = (RenderedImage) sources.get(0);
      RenderedImage image0 = (RenderedImage) sources.iterator().next();

      int width = image0.getWidth();
      int height = image0.getHeight();
      int depth = sources.size();
      int elements = image0.getData().getNumBands() / 2;   // the image is complex, it is a FFT after all

      CollectionImage source0 = this.shift(sources, hints);
      CollectionImage source1 = this.getRawFilter(filter, width, height, depth, elements, hints);
      CollectionImage filtered = this.multiply(source0, source1, hints);

      CollectionImage sinks = this.shift(filtered, hints);
      return sinks;
      }


//---------------------------
// Implemented methods from javax.media.jai.CollectionImageFactory
//---------------------------

   /**
    * Creates a {@code CollectionImage} that represents the result of applying
    * the requested operation once to each image in the collection.
    * @param   pb   the parameter block.
    * @param   hints   the rendering hints.
    * @return   the collection image containing the results.
    */
   @SuppressWarnings({ "unchecked", "nls" })
   public CollectionImage create(ParameterBlock pb, RenderingHints hints) {
   // the real type is CollectionImage,
   // it is OK to see it as a collection
   // of rendered images, which it is.
      Collection<RenderedImage> sources = (Collection<RenderedImage>) pb.getSource(0);

      SpectralFilter3D filter = this.getFilter(pb);
      int type = this.getDataType(pb);

      String[] pre_operations = new String[] {
         "applytocollection",
         "dft",
         };
      ParameterBlock[] pre_pbs = new ParameterBlock[] {
         new ParameterBlock().add("format").add(ParameterBlockUtil.createFormatParameterBlock(null, type)),
         new ParameterBlock(),
         };
      CollectionImage fft;
      {
         Collection<RenderedImage> collection = PipelineDescriptor.createCollection(sources, pre_operations, pre_pbs, hints);
         fft = CollectionImageUtil.asCollectionImage(collection);
      }

   // before doing the filtering, one could ask why the periodic shifting
   // is not done int the pre and post pipeline. the shifting parameter
   // block factory needs an image to calculates the default shifting
   // parameter. the shifting is done in the filter method.
      Collection<RenderedImage> cooked = this.filter(fft, filter, hints);

      String[] post_operations = new String[] {
         "idft",
         };
      ParameterBlock[] post_pbs = new ParameterBlock[] {
         new ParameterBlock(),
         };
      CollectionImage sinks;
      {
         Collection<RenderedImage> collection = PipelineDescriptor.createCollection(cooked, post_operations, post_pbs, hints);
         sinks = CollectionImageUtil.asCollectionImage(collection);
      }
      return sinks;
      }

   /**
    * It is impratical to perform the update.
    * @param old_pb   ignored
    * @param old_hints   ignored
    * @param new_pb   ignored
    * @param new_hints   ignored
    * @param old_image   ignored
    * @param op   ignored
    * @return always {@code null}.
    */
   public CollectionImage update(ParameterBlock old_pb, RenderingHints old_hints,
                                 ParameterBlock new_pb, RenderingHints new_hints,
                                 CollectionImage old_image,
                                 CollectionOp op) {
   // it is impracticable to perform the update
      CollectionImage new_image = null;
      return new_image;
      }

   }
